package com.example.administrator.share.login;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.administrator.share.R;


import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener{


    private Button btnWeChat;
    private Button btnQQ;
    private Button btnSina;
    private TextView tvName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ShareSDK.initSDK(getApplicationContext());
        initView();
    }

    private void initView() {
        btnWeChat = (Button) findViewById(R.id.btn_wechat);
        btnQQ = (Button) findViewById(R.id.btn_qq);
        btnSina = (Button) findViewById(R.id.btn_sina);
        tvName = (TextView) findViewById(R.id.name);
        btnWeChat.setOnClickListener(this);
        btnQQ.setOnClickListener(this);
        btnSina.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Platform platform=null;
        switch (v.getId()){
            case R.id.btn_wechat:
                platform= ShareSDK.getPlatform(Wechat.NAME);
                break;
            case R.id.btn_qq:
                platform=ShareSDK.getPlatform(QQ.NAME);
                break;
            case R.id.btn_sina:
                platform=ShareSDK.getPlatform(SinaWeibo.NAME);
                break;
        }
        login(platform);
    }

    private void login(Platform platform) {

        platform.removeAccount();
        platform.removeAccount(true);

        if (platform==null){
            return;
        }
        PlatformDb db=platform.getDb();
        //已经认证且未过期
        if (db.isValid()){
            tvName.setText(db.getUserName());
            return;
        }
        //没有认证
        platform.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                tvName.setText(hashMap.get("name").toString());
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
            }

            @Override
            public void onCancel(Platform platform, int i) {
            }
        });
        platform.showUser(null);
    }
}
